package com.rfid.project.web;

import java.text.DateFormat;
import java.util.List;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ui.Model;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springframework.data.domain.Page;

import biz.appframe.PageJsonBean;

import com.rfid.project.exception.CannotDelException;
import com.rfid.project.exception.CannotUpdateException;
import com.rfid.project.model.ProjectDelivery;
import com.rfid.project.model.ProjectDeliveryType;
import com.rfid.project.service.ProcessStatus;
import com.rfid.project.service.ProjectDeliveryService;
import com.rfid.project.service.ProjectDeliveryTypeService;
import com.rfid.project.service.ProjectProductService;
import com.rfid.project.model.Project;
import com.rfid.project.service.ProjectService;
import com.rfid.project.model.Product;
import com.rfid.project.service.ProductService;
import com.rfid.project.model.People;
import com.rfid.project.service.PeopleService;
import com.rfid.project.model.DeliveryWay;
import com.rfid.project.service.DeliveryWayService;

@Controller
public class ProjectDeliveryController {

	private static final Logger logger = LoggerFactory
			.getLogger(ProjectDeliveryController.class);

	@Autowired
	private ProjectDeliveryService projectDeliveryService;

	@Autowired
	private ProjectService projectService;

	@Autowired
	private ProductService productService;

	@Autowired
	private ProjectProductService projectProductService;

	
	@Autowired
	private PeopleService peopleService;

	@Autowired
	private DeliveryWayService deliveryWayService;

	@Autowired
	private ProjectDeliveryTypeService projectDeliveryTypeService;

	@RequestMapping(value = "/projectDeliverymgr")
	public String projectmgr(HttpServletRequest request,
			HttpServletResponse response, Model model) {

		List<Project> projects = projectService.findAll();
		model.addAttribute("projects", projects);

		List<Product> products = productService.findAll();
		model.addAttribute("products", products);

		List<People> peoples = peopleService.findAll();
		model.addAttribute("peoples", peoples);

		List<DeliveryWay> deliveryWays = deliveryWayService.findAll();
		model.addAttribute("deliveryWays", deliveryWays);

		List<ProjectDeliveryType> projectDeliveryTypes = projectDeliveryTypeService.findAll();
		model.addAttribute("projectDeliveryTypes", projectDeliveryTypes);

		return "projectDeliverymgr";
	}

	@RequestMapping(value = "/queryProjectDelivery")
	public String queryProjectDelivery(
			HttpServletRequest request,
			HttpServletResponse response,
			@RequestParam(value = "projectID", defaultValue = "-1") Long projectId,
			@RequestParam(value = "productID", defaultValue = "-1") Long productId,
			@RequestParam(value = "inputPerson", defaultValue = "-1") Long inputPersonId,
			@RequestParam(value = "checkPerson", defaultValue = "-1") Long checkPersonId,
			@RequestParam(value = "producer", defaultValue = "") String producer,
			@RequestParam(value = "projectCode", defaultValue = "") String projectCode,
			@RequestParam(value = "name", defaultValue = "") String name,
			@RequestParam(value = "batchNo", defaultValue = "") String batchNo,
			@RequestParam(value = "spec", defaultValue = "") String spec,
			@RequestParam(value = "unit", defaultValue = "") String unit,
			@RequestParam(value = "deliveryNumber", defaultValue = "") Integer deliveryNumber,
			@RequestParam(value = "deliveryDateBegin", defaultValue = "") Date deliveryDateBegin,
			@RequestParam(value = "deliveryDateEnd", defaultValue = "") Date deliveryDateEnd,
			@RequestParam(value = "ourHandler", defaultValue = "") String ourHandler,
			@RequestParam(value = "customerHandler", defaultValue = "") String customerHandler,
			@RequestParam(value = "deliveryAddress", defaultValue = "") String deliveryAddress,
			@RequestParam(value = "deliveryWayID", defaultValue = "-1") Long deliveryWayId,
			@RequestParam(value = "ProjectDeliveryTypeID", defaultValue = "-1") Long ProjectDeliveryTypeID,
			@RequestParam(value = "voucherNo", defaultValue = "") String voucherNo,
			@RequestParam(value = "remark", defaultValue = "") String remark,
			@RequestParam(value = "inputTimeBegin", defaultValue = "") Date inputTimeBegin,
			@RequestParam(value = "inputTimeEnd", defaultValue = "") Date inputTimeEnd,
			@RequestParam(value = "checkTimeBegin", defaultValue = "") Date checkTimeBegin,
			@RequestParam(value = "checkTimeEnd", defaultValue = "") Date checkTimeEnd,
			@RequestParam(value = "status", defaultValue = "") String status,
			@RequestParam(value = "warrantyDate", defaultValue = "") String warrantyDate,
			@RequestParam(value = "page", defaultValue = "1") Integer pageNumber,
			@RequestParam(value = "rows", defaultValue = "10") Integer pageSize,
			@RequestParam(value = "sort", defaultValue = "") String sort,
			@RequestParam(value = "order", defaultValue = "") String order,
			Model model) {
		Page<ProjectDelivery> items = projectDeliveryService.findAll(projectId,
				productId, inputPersonId, checkPersonId, producer, projectCode,
				name, batchNo, spec, unit, deliveryDateBegin, deliveryDateEnd,
				ourHandler, customerHandler, deliveryAddress, deliveryWayId,
				voucherNo, remark, inputTimeBegin, inputTimeEnd,
				checkTimeBegin, checkTimeEnd, status, warrantyDate, pageNumber,
				pageSize, sort, order);
		JSONObject object = new JSONObject();
		object.put("total", items.getTotalElements());
		JSONArray models = new JSONArray();

		for (ProjectDelivery item : items) {
			JSONObject mod = new JSONObject();
			capacityData(item, mod);

			models.add(mod);
		}
		object.put("rows", models);
		PageJsonBean.printObject(response, object);
		return null;
	}
	
	@RequestMapping(value = "/findProjectDelivery")
	public String findProjectDelivery(
			HttpServletRequest request,
			HttpServletResponse response,
			@RequestParam(value = "id", defaultValue = "-1") Long id,
			Model model) {
		ProjectDelivery projectDelivery = projectDeliveryService.findOne(id);
		JSONObject object = new JSONObject();
			JSONObject mod = new JSONObject();
			capacityData(projectDelivery, mod);
		object.put("success", true);
		object.put("data", mod);
		PageJsonBean.printObject(response, object);
		return null;
	}

	private void capacityData(ProjectDelivery item, JSONObject mod) {
		if(null == item){
			return;
		}
		mod.put("id", item.getId());
		mod.put("projectName", item.getProject().getName());
		Product project = item.getProduct();
		if(null == project){
			mod.put("productID", -1);
			mod.put("productName", "");
		}else{
			mod.put("productID", project.getId());
			mod.put("productName", project.getName());
		}
		mod.put("projectDeliveryTypeName", item.getProjectDeliveryType().getName());
		mod.put("projectID", item.getProject().getId());
		mod.put("inputPerson", item.getInputPerson().getId());
		mod.put("inputPersonName", item.getInputPerson().getName());
		
		People checkPerson = item.getCheckPerson();
		if (null == checkPerson) {
			mod.put("checkPerson", -1);
			mod.put("checkPersonName", "");
		} else {
			mod.put("checkPerson", checkPerson.getId());
			mod.put("checkPersonName", checkPerson.getName());
		}
		mod.put("producer", item.getProducer());
		mod.put("projectCode", item.getProjectCode());
		mod.put("name", item.getName());
		mod.put("batchNo", item.getBatchNo());

		String specContent = item.getSpec();
		mod.put("spec", specContent == null ? "" : specContent);
		mod.put("unit", item.getUnit());
		mod.put("deliveryNumber", item.getDeliveryNumber());
		mod.put("deliveryDate", com.rfid.project.util.DateUtil.dateTheDayToString(item.getDeliveryDate()));
		mod.put("ourHandler", item.getOurHandler());
		mod.put("customerHandler", item.getCustomerHandler());
		mod.put("deliveryAddress", item.getDeliveryAddress());
		mod.put("deliveryWayID", item.getDeliveryWay().getId());
		mod.put("deliveryWayName", item.getDeliveryWay().getName());
		mod.put("projectDeliveryTypeID", item.getProjectDeliveryType().getId());
		mod.put("voucherNo", item.getVoucherNo());
		mod.put("remark", item.getRemark());
		mod.put("inputTime", com.rfid.project.util.DateUtil.dateTheDayToString(item.getInputTime()));
		mod.put("checkTime", com.rfid.project.util.DateUtil.dateTheDayToString(item.getCheckTime()));
		mod.put("status", ProcessStatus.processStatusName(item.getStatus()));
		mod.put("statusCode", item.getStatus());
		mod.put("warrantyDate", item.getWarrantyDate());
	}

	@RequestMapping(value = "/editProjectDelivery", method = RequestMethod.POST)
	public String editProjectDelivery(HttpServletRequest request,
			HttpServletResponse response,
			@Valid ProjectDelivery projectDelivery, Model model,
			RedirectAttributes redirectAttributes) {
		People people = projectDelivery.getInputPerson();
		if(null == people || null == people.getId()){
			projectDelivery.setInputPerson((People)request.getSession().getAttribute("currentUser"));
		}
		projectDeliveryService.saveProjectDelivery(projectDelivery);

		JSONObject result = new JSONObject();
		result.put("success", true);
		PageJsonBean.printObject(response, result);
		return null;
	}

	@RequestMapping(value = "/getProjectDelivery")
	public String getProjectDelivery(HttpServletRequest request,
			HttpServletResponse response,
			@RequestParam(value = "id", defaultValue = "-1") Long id) {
		ProjectDelivery item = projectDeliveryService.findOne(id);
		JSONObject mod = new JSONObject();
		this.capacityData(item, mod);

		PageJsonBean.printObject(response, mod);
		return null;
	}
	
	@RequestMapping(value = "/checkProjectDelivery", method = RequestMethod.POST)
	public String checkProjectDelivery(
			HttpServletRequest request,
			HttpServletResponse response,
			@Valid ProjectDelivery projectDelivery) {
		People checkPerson = projectDelivery.getCheckPerson();
		if (null == checkPerson || null == checkPerson.getId()) {
			People currentUser = (People) request.getSession().getAttribute("currentUser");
			projectDelivery.setCheckPerson(currentUser);
		}
		JSONObject result = new JSONObject();
		boolean flag = true;
		try {
			projectDeliveryService.checkProjectDelivery(projectDelivery);
		} catch (CannotUpdateException e) {
			flag = false;
			result.put("msg", e.getMessage());
		}
		result.put("success", flag);
		PageJsonBean.printObject(response, result);
		return null;
	}

	@RequestMapping(value = "/commitProjectDelivery")
	public String commitProjectDelivery(HttpServletRequest request,
			HttpServletResponse response,
			@Valid ProjectDelivery projectDelivery) {
		JSONObject result = new JSONObject();
		boolean flag = true;
		this.projectDeliveryService.commitProjectDelivery(projectDelivery);
		result.put("success", flag);
		PageJsonBean.printObject(response, result);
		return null;
	}
	
	@RequestMapping(value = "/revocationProjectDeliveryFinishApply")
	public String revocationProjectDeliveryFinishApply(HttpServletRequest request,
			HttpServletResponse response, @Valid ProjectDelivery projectDelivery,
			Model model, RedirectAttributes redirectAttributes) {
		JSONObject result = new JSONObject();
		boolean flag = true;
		try {
			this.projectDeliveryService.revocationProjectDeliveryFinishApply(projectDelivery);
		} catch (CannotUpdateException e) {
			flag = false;
			result.put("msg", e.getMessage());
		}
		result.put("success", flag);
		PageJsonBean.printObject(response, result);
		return null;
	}

	@RequestMapping(value = "/delProjectDelivery")
	public String delProjectDelivery(HttpServletRequest request,
			HttpServletResponse response,
			@RequestParam(value = "id", defaultValue = "") Long id) {
		JSONObject result = new JSONObject();
		boolean flag = true;
		try {
			this.projectDeliveryService.deleteProjectDelivery(id);
		} catch (CannotDelException e) {
			flag = false;
			result.put("msg", e.getMessage());
		}
		result.put("success", flag);
		PageJsonBean.printObject(response, result);
		return null;
	}

	@InitBinder
	protected void initBinder(HttpServletRequest request,
			ServletRequestDataBinder binder) throws Exception {
		DateFormat dateFormat = com.rfid.project.util.DateUtil
				.getFormat("yyyy-MM-dd");
		dateFormat.setLenient(false);
		binder.registerCustomEditor(Date.class, new CustomDateEditor(
				dateFormat, true));
	}

}
